package cn.yuanqiao.archive.liyong.service.impl;

import cn.yuanqiao.archive.liyong.domain.YqDy;
import cn.yuanqiao.archive.liyong.domain.YqdyDa;
import cn.yuanqiao.archive.liyong.mapper.ListQueryMapper;
import cn.yuanqiao.archive.liyong.mapper.YqDyMapper;
import cn.yuanqiao.archive.liyong.mapper.YqdyDaMapper;
import cn.yuanqiao.archive.liyong.service.IYqdyDaService;
import cn.yuanqiao.archive.xiaoxitongzhi.domain.YqXxtz;
import cn.yuanqiao.archive.xiaoxitongzhi.service.IYqXxtzService;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.domain.DataScopeStaticValue;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 我的订阅Service业务层处理
 * 
 * @author sy
 * @date 2023-08-10
 */
@Service
public class YqdyDaServiceImpl implements IYqdyDaService 
{
    @Autowired
    private YqdyDaMapper yqdyDaMapper;

    @Autowired
    private YqDyMapper yqDyMapper;

    @Autowired
    ListQueryMapper listQueryMapper;

    @Autowired
    IYqXxtzService yqXxtzService;

    /**
     * 查询我的订阅
     * 
     * @param dyId 我的订阅
     * @return 我的订阅
     */
    @Override
    public YqdyDa selectYqdyDaByDyId(Long dyId)
    {
        YqdyDa yqdyDa = new YqdyDa();
        yqdyDa.setDyId(dyId);
        return yqdyDaMapper.selectYqdyDaByDyId(yqdyDa);
    }

    /**
     * 查询我的订阅列表
     * 
     * @param yqdyDa 我的订阅
     * @return 我的订阅
     */
    @Override
    public List<YqdyDa> selectYqdyDaList(YqdyDa yqdyDa)
    {
        return yqdyDaMapper.selectYqdyDaList(yqdyDa);
    }

    /**
     * 新增我的订阅
     * 
     * @param yqdyDa 我的订阅
     * @return 结果
     */
    @Override
    public int insertYqdyDa(YqdyDa yqdyDa)
    {
        return yqdyDaMapper.insertYqdyDa(yqdyDa);
    }

    /**
     * 修改我的订阅
     * 
     * @param yqdyDa 我的订阅
     * @return 结果
     */
    @Override
    public int updateYqdyDa(YqdyDa yqdyDa)
    {
        return yqdyDaMapper.updateYqdyDa(yqdyDa);
    }

    /**
     * 批量删除我的订阅
     * 
     * @param dyIds 需要删除的我的订阅主键
     * @return 结果
     */
    @Override
    public int deleteYqdyDaByDyIds(Long[] dyIds)
    {
        return yqdyDaMapper.deleteYqdyDaByDyIds(dyIds);
    }

    /**
     * 删除我的订阅信息
     * 
     * @param yqdyDa 我的订阅主键
     * @return 结果
     */
    @Override
    public int deleteYqdyDaByDyId(YqdyDa yqdyDa)
    {
        return yqdyDaMapper.deleteYqdyDaByDyId(yqdyDa);
    }

    @Override
    public Map<String, List> selectYqdyDaListByDyId(Long dyId)
    {
        Map<String, List> map = new HashMap<>();
        List<Map> result = new ArrayList<>();
        String title;
        YqdyDa yqdyDa = new YqdyDa();
        yqdyDa.setDyId(dyId);
        List<YqdyDa> yqdyDaList = yqdyDaMapper.selectYqdyDaListByDyId(yqdyDa);
        for (YqdyDa entry:yqdyDaList){
            Map<String,Object> data = new HashMap<>();
            title = yqdyDaMapper.selectDaTitle(entry);
            data.put("dyId",dyId);
            data.put("title",title);
            data.put("daId",entry.getDaId());
            data.put("tjsj",entry.getTjsj());
            data.put("subTableName",entry.getSubTableName());
            data.put("type",entry.getType());
            data.put("state",entry.getState());
            SysUser user = SecurityUtils.getLoginUser().getSysUser();
            boolean allMatch = false;
            List<SysRole> roles = user.getRoles();
            if (roles != null && roles.size() > 0) {
                allMatch = roles.stream().anyMatch(a -> a.getRoleKey().trim().equals("dagly"));
            }
            if (allMatch) {
                data.put("is_borrowing_car", "0");
            }else{
                data.put("is_borrowing_car", "1");
            }
            result.add(data);
        }
        map.put("result",result);
        map.put("yqdyDaList",yqdyDaList);
        return map;
    }

    @Override
    public void search(String tenantCode){
        int num = 0;
        int batchSize = 1000; // 设置批量插入的大小
        String updateTime;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date tjsj = new Date();
        String gjc;
        String yqDyDaTbale = tenantCode + "_YQDY_DA";
        String itemTable = tenantCode + "_YQITEM";
        String folderTable = tenantCode + "_YQFOLDER";
        String daTable = tenantCode + "_YQDA";
        String yqXxtzTable = tenantCode + "_YQXXTZ";
        String yqXxfbfwTable = tenantCode + "_YQXXFBFW";
//        LoginUser user = SecurityUtils.getLoginUser();
        YqDy yqDy1 = new YqDy(tenantCode);
//        yqDy1.setTableName(tenantCode+"_YQDY");
        List<YqDy> yqDyList = yqDyMapper.selectYqDyListAll(yqDy1);
        tjsj = DateUtils.getNowDate();
        for (YqDy yqDy:yqDyList){
            updateTime = (yqDy.getZxsj() != null) ? sdf.format(yqDy.getZxsj()) : "0";
            gjc = yqDy.getGjc().replaceAll("^，+|，+$", "").replaceAll("，+", "|");

            //将查询到的档案信息插入到订阅档案中间表
            //
//            num = yqdyDaMapper.restock(yqDyDaTbale,yqDy.getDyId(), tjsj, gjc, updateTime , itemTable, folderTable, daTable);

            //查询档案
            List<Map<String, Object>> data = yqdyDaMapper.selectDa(yqDy.getDyId(),yqDy.getCreatorId(), tjsj, gjc, updateTime , itemTable, folderTable, daTable);
            if (data.size()==0){
                continue;
            }
            //判断权限
            String menuId = yqdyDaMapper.selectMenuId(tenantCode,tenantCode.toUpperCase());
            if (StringUtils.isEmpty(menuId)){
                return;
            }
            List<Map<String, Object>> authority = authority(data, menuId, tenantCode);
            //将档案信息插入到订阅档案中间表
            if (ObjectUtils.isEmpty(authority)) {
                continue;
            }
//            num = yqdyDaMapper.restockYqdyDa(yqDyDaTbale,authority);
            for (int i = 0; i < authority.size(); i += batchSize) {
                int end = Math.min(i + batchSize, authority.size());
                List<Map<String, Object>> batchAuthority = authority.subList(i, end);
                num += yqdyDaMapper.restockYqdyDaBatch(yqDyDaTbale, batchAuthority);
            }

//            num = yqdyDaMapper.restock("YQDY_DA",yqDy.getDyId(), tjsj, gjc, updateTime , itemTable, folderTable, daTable);
            //更新订阅表的最新消息时间和消息条数
            if (num>0){
                yqDy.setXxsm((yqDy.getXxsm()==null?0:yqDy.getXxsm())+num);
                yqDy.setZxsj(tjsj);
                yqDy.setTableName(tenantCode+"_YQDY");
                yqDyMapper.updateYqDy(yqDy);
                String msg = "您有"+yqDy.getXxsm()+"条新的“"+yqDy.getGjc()+"”的订阅消息未读。";
                YqXxtz yqXxtz = new YqXxtz(tenantCode);
                yqXxtz.setId(SnowflakeIdGenerator.generateId());
                yqXxtz.setMsg(msg);
                yqXxtz.setType(1);
                yqXxtz.setIsRead(0);
                yqXxtz.setRecordId(yqDy.getDyId());
                yqXxtz.setRecipientsId(yqDy.getCreatorId());
                yqXxtz.setCreateTime(tjsj);
                yqXxtzService.insertYqXxtzAndYqXxfbfw(yqXxtz,tenantCode);
                //  yqdyDaMapper.insertYqXxtz(yqXxtzTable,yqXxfbfwTable,SnowflakeIdGenerator.generateId(),msg,yqDy.getDyId(),tjsj,yqDy.getCreatorId());//yqdyDaMapper.insertYqXxtz(yqXxtzTable,yqXxfbfwTable,SnowflakeIdGenerator.generateId(),msg,yqDy.getDyId(),tjsj,yqDy.getCreatorId());
            }
        }
    }

    @Override
    public void search(String tenantCode,YqDy yqDy){
        int num = 0;
        int batchSize = 1000; // 设置批量插入的大小
        String updateTime;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date tjsj = new Date();
        String gjc;
        String yqDyDaTbale = tenantCode + "_YQDY_DA";
        String itemTable = tenantCode + "_YQITEM";
        String folderTable = tenantCode + "_YQFOLDER";
        String daTable = tenantCode + "_YQDA";
        String yqXxtzTable = tenantCode + "_YQXXTZ";
        String yqXxfbfwTable = tenantCode + "_YQXXFBFW";
        LoginUser user = SecurityUtils.getLoginUser();

        tjsj = DateUtils.getNowDate();

        updateTime = (yqDy.getZxsj() != null) ? sdf.format(yqDy.getZxsj()) : "0";
        gjc = yqDy.getGjc().replaceAll("^，+|，+$", "").replaceAll("，+", "|");
        //将查询到的档案信息插入到订阅档案中间表
//            num = yqdyDaMapper.restock(yqDyDaTbale,yqDy.getDyId(), tjsj, gjc, updateTime , itemTable, folderTable, daTable);

        //查询档案
        List<Map<String, Object>> data = yqdyDaMapper.selectDa(yqDy.getDyId(),yqDy.getCreatorId(), tjsj, gjc, updateTime , itemTable, folderTable, daTable);
        if (data.size()==0){
            return;
        }
        //判断权限
        String menuId = yqdyDaMapper.selectMenuId(tenantCode.toLowerCase(),tenantCode.toUpperCase());
        if (StringUtils.isEmpty(menuId)){
            return;
        }
        List<Map<String, Object>> authority = authority(data, menuId, tenantCode);
        //将档案信息插入到订阅档案中间表
        if (authority.size()>=1){
//                num = yqdyDaMapper.restockYqdyDa(yqDyDaTbale,authority);
            for (int i = 0; i < authority.size(); i += batchSize) {
                int end = Math.min(i + batchSize, authority.size());
                List<Map<String, Object>> batchAuthority = authority.subList(i, end);
                num += yqdyDaMapper.restockYqdyDaBatch(yqDyDaTbale, batchAuthority);
            }
        }
        //更新订阅表的最新消息时间和消息条数
        if (num>0){
            yqDy.setXxsm((yqDy.getXxsm()==null?0:yqDy.getXxsm())+num);
            yqDy.setZxsj(tjsj);
            yqDy.setTableName(tenantCode+"_YQDY");
            yqDyMapper.updateYqDy(yqDy);
            String msg = "您有"+yqDy.getXxsm()+"条新的“"+yqDy.getGjc()+"”的订阅消息未读。";
            YqXxtz yqXxtz = new YqXxtz();
            yqXxtz.setId(SnowflakeIdGenerator.generateId());
            yqXxtz.setMsg(msg);
            yqXxtz.setType(1);
            yqXxtz.setIsRead(0);
            yqXxtz.setRecordId(yqDy.getDyId());
            yqXxtz.setRecipientsId(yqDy.getCreatorId());
            yqXxtz.setCreateTime(tjsj);
            yqXxtzService.insertYqXxtzAndYqXxfbfw(yqXxtz);
//                yqdyDaMapper.insertYqXxtz(yqXxtzTable,yqXxfbfwTable,SnowflakeIdGenerator.generateId(),msg,yqDy.getDyId(),tjsj,yqDy.getCreatorId());
        }

    }

    /**
     * 修改消息状态
     *
     * @param yqdyDa 我的订阅
     * @return 我的订阅
     */
    @Override
    public void updateYqdyDaState(YqdyDa yqdyDa)
    {
        //判断状态
        if (yqdyDa.getState()==0){
            //执行修改状态
//            if (yqdyDa.getDyId() == null || yqdyDa.getDyId() == 0) {
//                yqdyDa = yqdyDaMapper.selectYqdyDaByDyDaId(yqdyDa);
//            }
            String tenantCode =  SecurityUtils.getTenantCode();
            String yqDyTable = tenantCode + "_YQDY";
            String yqDyDaTable = tenantCode + "_YQDY_DA";
            String yqXxtzTable = tenantCode + "_YQXXTZ";
            String yqXxfbfwTable = tenantCode + "_YQXXFBFW";
            LoginUser user = SecurityUtils.getLoginUser();
            yqdyDaMapper.updateYqdyDaState(yqDyTable,yqDyDaTable,yqdyDa.getDyId(),yqdyDa.getDaId());
//            yqdyDaMapper.updateYqdyDaState("YQDY","YQDY_DA",yqdyDa.getDyId(),yqdyDa.getDaId());
            YqDy yqDy = new YqDy();
            yqDy.setDyId(yqdyDa.getDyId());
            //修改YQXXTZ表的消息
            yqDy = yqDyMapper.selectYqDyByDyId(yqDy);
            String msg;
            if (yqDy.getXxsm()>0){
                //未读
                msg = "您有"+yqDy.getXxsm()+"条新的“"+yqDy.getGjc()+"”的订阅消息未读。";
                yqdyDaMapper.updateYqXxTzMsg(yqXxtzTable,yqXxfbfwTable,yqdyDa.getDyId(),msg,user.getUserId());
//                yqdyDaMapper.updateYqXxTzMsg("YQXXTZ",yqdyDa.getDyId(),msg);
            }else {
                //标为已读
                msg = "您有0条新的“"+yqDy.getGjc()+"”的订阅消息未读。";
                yqdyDaMapper.updateYqXxTzRead(yqXxtzTable,yqXxfbfwTable,yqdyDa.getDyId(),msg,user.getUserId());
//                yqdyDaMapper.updateYqXxTzRead("YQXXTZ",yqdyDa.getDyId());
            }
        }
//        return 1;
    }

    /**
     * 借阅权限
     *
     * @param dataList
     * @param menuId
     * @return
     */
    public List<Map<String, Object>> authority(List<Map<String, Object>> dataList, String menuId,String tenantCode) {
        if (ObjectUtils.isEmpty(dataList)) {
            return null;
        }
//        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
//        boolean allMatch = false;
//        if (roles != null && roles.size() > 0) {
//            allMatch = roles.stream().anyMatch(a -> a.getRoleName().trim().equals("档案管理员"));
//        }
        Iterator<Map<String, Object>> iterator = dataList.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> data = iterator.next();
//            for (Map<String, Object> data : dataList) {
            //根据用户ID查询角色列表
//            List<SysRole> roles = yqdyDaMapper.selectRolePermissionByUserIdAndTenantCode((Long) data.get("USER_ID"),tenantCode);
            //
            SysUser sysUser = yqdyDaMapper.selectUserById(Long.valueOf(data.get("USER_ID").toString()));
            List<SysRole> roles = sysUser.getRoles();
            boolean allMatch = false;
            if (roles != null && roles.size() > 0) {
                allMatch = roles.stream().anyMatch(a -> a.getRoleName().trim().equals("档案管理员"));
            }
            //is_borrowing_car   0 不需要借阅 1 需要借阅
            int isBorrowingCar = 1;
            if (allMatch) {
                data.put("is_borrowing_car", "0");
                continue;
            }
            if (data.containsKey("IS_OPENS")) {
                //IS_OPENS  0 不开放  1 开放
                String isOpens = data.get("IS_OPENS") == null ? "" : data.get("IS_OPENS").toString();
                if ("1".equals(isOpens)) {
                    data.put("is_borrowing_car", "0");
                    continue;
                }
            }
            String tableName = data.get("SUB_TABLE_NAME") == null ? "" : data.get("SUB_TABLE_NAME").toString();
            String tablenametype = tableName.substring(tableName.length() - 3, tableName.length() - 2);
            if (isBorrowingCar == 1) {
                if (data.containsKey("CREATE_ID")) {
                    StringBuilder sql = new StringBuilder();
                    //归档处室
                    String gdcsId = null;
                    if (data.containsKey("GDCS_ID")) {
                        gdcsId = data.get("GDCS_ID") == null ? "" : data.get("GDCS_ID").toString();
                    }
                    if ("F".equalsIgnoreCase(tablenametype)) {//档案层
                        sql.append(" FILE_TABLE_NAME = '");
                    } else if ("V".equalsIgnoreCase(tablenametype)) {//案卷层
                        sql.append(" FOLDER_TABLE_NAME = '");
                    } else if ("X".equalsIgnoreCase(tablenametype)) {//项目层
                        sql.append(" ITEM_TABLE_NAME = '");
                    }
                    sql.append(tableName).append("' ");
                    //
//                    String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
                    //创建人id
                    String createId = data.get("CREATE_ID") == null ? "" : data.get("CREATE_ID").toString();
                    String categoryId = listQueryMapper.selectAppData(tenantCode + Constants.BIG_TABLE_NAME, " ID ", sql.toString());
                    if (roleTree(menuId, createId, categoryId, gdcsId,tenantCode,sysUser)) {
                        isBorrowingCar = 0;
                    }
                }
            }
            //       }
            data.put("is_borrowing_car", isBorrowingCar);
            if (data.get("is_borrowing_car").equals("1")){
                iterator.remove();
            }
        }
        return dataList;
    }

    /**
     * 角色判断
     *
     * @param menuId     菜单id
     * @param createId   门类id
     * @param categoryId 门类和元数据方案关联id
     *                   gdcsId 归档处室
     * @return
     */
    public boolean roleTree(String menuId, String createId, String categoryId, String gdcsId,String tenantCode,SysUser sysUser) {
//        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        boolean b = false;
//        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
//        Long dept = SecurityUtils.getLoginUser().getUser().getDeptId();
        List<SysRole> roles = sysUser.getRoles();
        Long dept =sysUser.getDeptId();
        if (roles != null && roles.size() > 0) {
            for (SysRole role : roles) {
                StringBuilder sqlStringTr = new StringBuilder();
                //查询角色关联档案门类
                sqlStringTr.append(" id in ( select tree_id from ").append(tenantCode + "_TREESROLE")
                        .append(" where  ROLE_ID = '").append(role.getRoleId()).append("' AND MENU_ID = '").append(menuId).append("' ) and category_id = '")
                        .append(categoryId).append("' ");
                String countCgId = listQueryMapper.selectAppData(tenantCode + Constants.ABLE_TREES, " COUNT(*) ", sqlStringTr.toString());
                if (!"0".equals(countCgId)) {
                    StringBuilder sqlString = new StringBuilder();
                    String dataScope = role.getDataScope();
                    String userIdNum = "0";
                    if (DataScopeStaticValue.DATA_SCOPE_ALL.equals(dataScope)) {
                        return true;
                    } else if (DataScopeStaticValue.DATA_SCOPE_CUSTOM.equals(dataScope)) {
                        sqlString.append(" su.dept_id in ( select dept_id from sys_role_dept where ROLE_ID = '")
                                .append(role.getRoleId()).append("' ) and su.user_id= '").append(createId).append("' ");
                        userIdNum = listQueryMapper.selectAppData(" sys_user su ", " COUNT(*) ", sqlString.toString());
                    } else if (DataScopeStaticValue.DATA_SCOPE_DEPT.equals(dataScope)) {
                        sqlString.append(" su.dept_id in ( select dept_id from sys_dept where dept_id = '")
                                .append(dept).append("' ) and su.user_id=  '").append(createId).append("' ");
                        userIdNum = listQueryMapper.selectAppData(" sys_user su ", " COUNT(*) ", sqlString.toString());
                    } else if (DataScopeStaticValue.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                        sqlString.append(" su.dept_id in ( select dept_id from sys_dept where dept_id = '")
                                .append(dept).append("' or find_in_set( '").append(dept).append("' , ancestors )) and su.user_id=  '")
                                .append(createId).append("' ");
                        userIdNum = listQueryMapper.selectAppData(" sys_user su ", " COUNT(*) ", sqlString.toString());
                    } else if (DataScopeStaticValue.DATA_SCOPE_SELF.equals(dataScope)) {
                        if (String.valueOf(SecurityUtils.getUserId()).equals(createId)) {
                            return true;
                        }
                    } else if (DataScopeStaticValue.DATA_SCOPE_DEPT_CUSTOM.equals(dataScope)) {
                        if (StringUtils.isNotBlank(gdcsId)) {
                            sqlString.append(" ROLE_ID='").append(role.getRoleId()).append("' and dept_id=  '")
                                    .append(gdcsId).append("' ");
                            userIdNum = listQueryMapper.selectAppData(" sys_role_dept ", " COUNT(*) ", sqlString.toString());
                        }
                    }
                    if (!"0".equals(userIdNum)) {
                        return true;

                    }
                }
            }
        }
        return b;
    }

}
